<template>
	<view v-if="showCon">
		<view class="c-block" v-if="sp.id==null||sp.id==''">
			<view class="c-title">问卷小程序22 - CSMWJ</view>
			<view class="c-title">Questionnaire applet - CSMWJ</view>
			<u-line></u-line>
			<view class="c-content">欢迎使用本小程序，如有问题请联系管理员</view>
			<view class="c-content">Welcome to use this small program, if you have any questions, please contact the
				administrator</view>
			<u-line></u-line>
			<view class="c-title" style="text-align: right;">Chen Shiming</view>
			<view class="c-title" style="text-align: right;">2021/03/20</view>
		</view>

		<view :style="sr.paper.themelogodivstyle">
			<image :src="sr.paper.themelogoimage" mode="heightFix" style="height: 40px;"
				v-if="sr.paper.themelogoimage!=null && sr.paper.themelogoimage!=''"></image>
		</view>

		<view class="c-block" v-if="sr.paper.themebannertype=='STRING'"
			:style="sr.paper.themebannerstringstyle+';'+sr.paper.themebannerstringdivstyle">
			{{sr.paper.themebannerstring}}
		</view>
		<u-image :src="sr.paper.themebannerimage" class="zxb-img" width="100%" mode="widthFit"
			v-if="sr.paper.themebannertype=='IMAGE'&&sr.paper.themebannerimage!=null && sr.paper.themebannerimage!=''">
		</u-image>
		<u-swiper :list="sr.paper.themebannerimages" imgMode="aspectFill" keyName="image"
			v-if="sr.paper.themebannertype=='IMAGES'&&sr.paper.themebannerimages!=null && sr.paper.themebannerimages!=''">
		</u-swiper>

		<view class="c-block-full" v-if="param.currentpage=='displayPaper'">
			<view class="a-top-notice" v-if="sr.paper.status!='normal'">{{$t('csmwj.msg.draft_paper_tips')}}}
			</view>
			<view class="a-top-notice-fillblank" v-if="sr.paper.status!='normal'"></view>
			<view class="c-block z-item2 z-item4" v-if="sr.paper.themetitleshow=='Y'"
				:style="sr.paper.themetitledivstyle+';'+sr.paper.themetitlefont">
				<view>{{sr.paper.name}}</view>
			</view>
      
			<view v-if="param.outintime===false">
				<!-- <u-line-progress v-if="sr.paper.cfghastimelimit=='Y'"
					style="position: fixed;left: 0px;top:0px;width:100%" :round="false" active-color="#2979ff"
					:percent="param.usedsecondpecent" striped-active striped></u-line-progress>
				<view v-if="sr.paper.cfghastimelimit=='Y'" style="height: 30rpx;"></view> -->
				<c-parsefg :tpl="sr.questionjson" :paper="sr.paper" ref="parse"></c-parsefg>
				<view class="c-block">
					<!-- <u-button v-if="sr.paper.themesubmitstring==null||sr.paper.themesubmitstring==''" type="primary"
						@click="submit" :style="sr.paper.themesubmitdivstyle">{{$t('common.submit')}}</u-button>
					<u-button v-if="sr.paper.themesubmitstring!=null&&sr.paper.themesubmitstring!=''"  color="red"
						@click="submit" :style="sr.paper.themesubmitdivstyle">{{sr.paper.themesubmitstring}}</u-button> -->
					<button :style="sr.paper.themesubmitdivstyle" @click="submit">
						{{(sr.paper.themesubmitstring!=null&&sr.paper.themesubmitstring!='')?sr.paper.themesubmitstring:$t('ccore.btn.submit')}}
					</button>
				</view>

			</view>
			<view class="c-block">&nbsp;&nbsp;</view>
			<view class="c-block" v-if="param.outintime===true">
				<view class="c-title" v-if="param.now<sr.paper.cfgbegintime">{{$t('csmwj.msg.answer_notbegin')}}
				</view>
				<view class="c-title" v-if="param.now>sr.paper.cfgendtime">{{$t('csmwj.msg.answer_alreadyend')}}
				</view>
				<view class="c-content">{{$t('csmwj.label.cfgbegintime')}}:
					{{sr.paper.cfgbegintime | date('yyyy-mm-dd hh:MM')}}
				</view>
				<view class="c-content">{{$t('csmwj.label.cfgendtime')}}:
					{{sr.paper.cfgendtime | date('yyyy-mm-dd hh:MM')}}
				</view>
			</view>
		</view>
		<view class="c-block h-over" v-if="param.currentpage=='displayPageResult'"
			style="text-align: center;line-height: 60rpx;">
			<view class="c-title">{{sr.paper.cfgresultmsg}}</view>
      <view @click="weixin_ClosePage" class="btn" :style="sr.paper.themesubmitdivstyle">退出</view>
			<u-image :src="sr.paper.cfgresultmsgimage"
				v-if="sr.paper.cfgresultmsgimage!=null && sr.paper.cfgresultmsgimage!=''" width="100%" mode="widthFix">
			</u-image>
			<view class="u-p-t-20">
				<u-button v-if="sr.paper.cfgmaxanswercount > sr.usercount" @click="clickAgain">
					{{$t('csmwj.btn.answer_again')}}
				</u-button>
			</view>
		</view>

		<view class="a-changeaccount" @click="clickChangeAccount">&nbsp;</view>
    
    

	</view>

  <view class="body" v-else>请用微信打开 ···</view>
</template>
<style>
	.a-changeaccount {
		text-align: right;
		font-size: 11px;
		padding-right: 10px;
	}
  .btn{width: 100px !important; border-radius: 6rpx; margin: 260rpx auto 0;}
  .h-over{width: 100%; height: 100vh; padding-top: 20vh; box-sizing: border-box;}
</style>
<script>
 

	//import clogin from '@/static/assets/clogin/js/clogin.js'
	import config from '@/common/config'

	export default {
		data() {
			return {
				options: null,
				//clogin: clogin,
				si_save: null,
				si_answer: null,
				param: {
					now: null,
					needauthorize: null,
					openid: null,
					/**
					 * displayPaper:显示问卷,待用户回答
					 * displayPageResult: 已经提交问卷
					 */
					currentpage: null,
					//是否在问卷时间内
					outintime: null,
					// usedsecond: 0, //已经使用了的时间
					// usedsecondpecent: 0, //已经时间百分比
				},
				sp: {
					id: null,
					mode: null, //themepreview:皮肤设置模式
				},
				sr: {
					paper: [],
					questionjson: [],
					usercount: 0,
					doing_userpaper: {}
				},
        showCon:false
			}
		},
		mounted() {
			if (window) {
				window.themepreview = this.themepreview;
			}
		},
		onLoad(options) {
			let that = this;
			console.log('onLoad');
			
			that.sp.id = options.id;
			that.sp.mode = options.mode;
			

			let scene = options.scene;
			if (scene != null) {
				console.log(scene);
				let pp = decodeURIComponent(scene);
				let pps = pp.split("&");
				let ppjson = {};
				for (let i = 0, j = pps.length; i < j; i++) {
					let iitem = pps[i].split("=");
					ppjson[iitem[0]] = iitem[1];
				}
				if (ppjson.id != null && ppjson.id != "") {
					that.sp.id = ppjson.id;
				}
			}

			this.options = options;
      
      this.showCon = this.isWeiXin(options.open_type)
			//that.cinit(options);
		},
		onShow() {
			let that = this;
			console.log('onShow');
			that.param.now = new Date().getTime() / 1000;
			//语言注入
			let locales = (that.options.locales!=null&&that.options.locales!='') ? that.options.locales : 'zh';
			that.$i18n.locale = locales;

			//皮肤设置预览,读取数据
			if (that.sp.mode == "themepreview") {
				that.param.currentpage = 'displayPaper';
				that.$u.c.ajaxget('csmwj/csmwj/paper', {
					'id': that.sp.id
				}, function(res) {
					that.sr.paper = res.paper;

					that.sr.questionjson = res.questionjson;
					that.param.outintime = false;
					that.sr.paper.themebannerimages = that.$u.c.uswiperAdjustImages(that.sr.paper
						.themebannerimages);
				});
				return;
			}
			//登录init

			that.cinit(that.options);
		},
		methods: {
      weixinClosePage() {
           if (typeof WeixinJSBridge == "undefined") {
               if (document.addEventListener) {
                   document.addEventListener('WeixinJSBridgeReady', weixin_ClosePage, false);
               } else if (document.attachEvent) {
                   document.attachEvent('WeixinJSBridgeReady', weixin_ClosePage);
                   document.attachEvent('onWeixinJSBridgeReady', weixin_ClosePage);
               }
           } else {
               this.weixin_ClosePage();
           }
       },
       weixin_ClosePage() {
           WeixinJSBridge.call('closeWindow');
       },
      
      
      isWeiXin(type) {
          var ua = navigator.userAgent.toLowerCase();
          if(type == 1){
            return true;
          }else if (ua.indexOf('micromessenger') > -1) {
            return true; // 在微信中打开
          } else {
            return false; // 在普通浏览器中打开
          }
      },
			cinit(options) {
				let that = this;
				that.$u.clogin.init(options, function(token, mobile, third) {
					that._initPaperPage(false);
				});
				setTimeout(function() {
					if (!that.$u.clogin.getIsLogined() && that.showCon) {
						console.log('unlogined');
						that.$u.c.showModal({
							title: that.$t('clogin.msg.unloginedtips'),
							success: (res) => {
								if (res.confirm) {
									that.$u.clogin.directLoginPage();
								} else {
									that.$u.clogin.clearSessionUserinfo();
									uni.navigateBack({});
								} 
							}
						})
					}
				}, 2000)
				return;
			},			
			/**
				// window.themepreview({
				// 	"themebannertype": "STRING",
				// 	"themebannerstring": "xx33333333333",
				// 	"themebannerstringstyle": "font-size:38px;color:yellow;font-weight:bold;",
				// 	"themebannerstringdivstyle": "background-color:blue;text-align:center",
				// 	"themebannerimage": "http://133.fa.net/uploads/20220410/d3f610bb684cb727a2e7b06f8164bec2.jpg",
				// 	"themebannerimages": "http://133.fa.net/uploads/20220410/d3f610bb684cb727a2e7b06f8164bec2.jpg,http://133.fa.net/uploads/20220410/d3f610bb684cb727a2e7b06f8164bec2.jpg",
				// 	"themelogoimage": "http://133.fa.net/assets/img/qrcode.png",
				// 	"themelogodivstyle": "background-color:red;text-align:right;padding:10px 10px 10px 10px;",
				// 	"themetitlefont": "color:green;font-size:55px;font-weight:bold;",
				// 	"themetitledivstyle": "background-color:yellow",
				// 	"themequestionfont": "font-size:18px;color:yellow;font-weight:bold;",
				// 	"themequestiondivstyle": "background-color:red;",
				// 	"themeoptionsfont": "font-size:12px;color:#00f000;font-weight:bold;",
				// 	"themeoptionsdivstyle": "background-color:yellow;",
				// 	"themesubmitstring": "SSubmit",
				// 	"themesubmitdivstyle": "background-color:yellow;",
				// 	"themetitleshow": "Y",
				// 	"themequestionnoshow": "N",
				// 	"themewelcomefont": "font-size:24px;color:#333333;background-color:red;",
				// 	"themewelcomedivstyle": "border:1px solid red;",
				// 	"themeendfont": "font-size:24px;color:#111111;background-color:red;",
				// 	"themeendedivstyle": "border:1px solid red;"		
				// });
			 */
			themepreview(themes) {
				let that = this;
				for (var index in themes) {
					this.sr.paper[index] = themes[index];
				}
				that.sr.paper.themebannerimages = that.$u.c.uswiperAdjustImages(that.sr.paper.themebannerimages);
				uni.setNavigationBarTitle({
					title: that.sr.paper['themetopnavigationtitle']
				})
				console.log("themepreview=", this.sr.paper);
			},
			reload() {
				console.log('reload');
			},
			submit: function() {
				let that = this;
				let ret = that.$refs.parse.__submit();
        console.log('ret------>', ret)
        // return
				// 如果是草稿状态
				if (that.sr.paper.status != 'normal') {
					that.$u.c.showModal({
						title: that.$t('csmwj.msg.draft_paper_tips')
					})
					return;
				}

				if (ret !== false) {
					uni.showLoading({
						title: 'Waiting'
					});
					that._saveorsubmituserpaper('submit', ret);

					if (that.si_save != null) {
						clearInterval(that.si_save);
					}
					if (that.si_answer != null) {
						clearInterval(that.si_answer);
					}
				}
			},
			clickAgain: function() {
				let that = this;
				that._initPaperPage(true);
			},
			clickChangeAccount: function() {
				let that = this;
				that.$u.clogin.logout();
				//that.cinit(that.options);
				that.$u.route({
					url: 'pages/csmwj/paper/list'
				});
			},
			/**
			 * spa. 先判定是显示问卷(如果没有回答过,或在未打完),还是显示问卷结果
			 * spb. 根据spa,显示对应的情况
			 * 		显示问卷
			 *      spb-1. 是否在有效期日内
			 *      spb-2. 如果在有效期,则是否有续答
			 * 		spb-3. 如果没有续答, 则创建userpage
			 * 		
			 */
			_initPaperPage: function(isForceDsipalyPaper) {
				let that = this;
				that.$u.c.ajaxget('csmwj/csmwj/paper', {
					'id': that.sp.id
				}, function(res) {
					that.sr.paper = res.paper;
					that.sr.questionjson = res.questionjson;
					that.sr.usercount = res.usercount;
					that.sr.doing_userpaper = res.doing_userpaper;
					//that.$i18n.locale = (that.sr.paper.locales == 'en') ? 'en' : 'zh';
					//that.sr.paper.themebannerimages = that.$u.c.uswiperAdjustImages(that.sr.paper.themebannerimages);
					that.sr.paper.themebannerimages = that.$u.c.uswiperAdjustImages(that.sr.paper
						.themebannerimages);

					uni.setNavigationBarTitle({
						title: that.sr.paper.themetopnavigationtitle
					})

					// spa
					if (that.sr.usercount == 0 || that.sr.doing_userpaper != null || isForceDsipalyPaper ===
						true) {
						that.param.currentpage = 'displayPaper';
					} else {
						that.param.currentpage = 'displayPageResult';
					}
					// spb
					switch (that.param.currentpage) {
						case "displayPaper":
							// spb-1
							if (that.sr.paper.cfghasdatelimit == 'Y') {
								if (that.param.now < that.sr.paper.cfgbegintime || that.param.now > that.sr
									.paper.cfgendtime) {
									that.param.outintime = true;
								} else {
									that.param.outintime = false;
								}
							} else {
								that.param.outintime = false;
							}

							if (that.param.outintime === false) {
								// spb-2. 果在有效期,且有未答完成,则提示
								if (that.sr.doing_userpaper != null) {
									that.$u.c.showModal({
										title: 'Tips',
										content: that.$t(
											'csmwj.msg.continue_last_answer'
										), //'您上一次答题未完成，请继续答题。',
										confirmText: "OK",
										showCancel: false,
										success: (res) => {
											that._startAnswer();
										}
									});
								} else {
									that._startAnswer();
								}

							}
							break;
						case "displayPageResult":
							break;
					}




					uni.hideLoading();
				})
			},
			/**
			 * spa. 如果非续答,则商城userpaper
			 * spb. 启动倒计时定时器和自动保存定时器
			 */
			_startAnswer: function() {
				let that = this;

				// spa.
				if (that.sr.doing_userpaper == null && that.sr.paper.status == 'normal') {
					that.$u.c.ajaxpost('csmwj/csmwj/createuserpage', {
						'id': that.sp.id,
					}, function(res) {
						that.sr.doing_userpaper = res.userpaper;
						that._startAnswer2RunCronAndProcess();
					})
				} else {
					that._startAnswer2RunCronAndProcess();
				}
			},
			/**
			 * 启动倒计时定时器和自动保存定时器
			 * 前台:需要先生成userpage
			 * 
			 * spa. 自动保存定时器
			 * spb. 启动倒计时定时器
			 * 		spb-1. 如果到了时间自动提交,并关闭定时器
			 */
			_startAnswer2RunCronAndProcess: function() {
				let that = this;
				//spa.
				that._cronSaveUserpage();
			},
			/**
			 * 保存或者提交userpage
			 * @param {Object} operate  submit=提交,save=保存,forcesubmit=强制提交
			 * @param {Object} ret
			 */
			_saveorsubmituserpaper(operate, ret) {
				let that = this;

				console.log("that.sr.doing_userpaper=", that.sr.doing_userpaper);
				console.log('----------',(new Date().getTime() / 1000 - that.param.now),new Date().getTime() / 1000 ,that.param.now);
				that.$u.c.ajaxpost('/csmwj/csmwj/saveorsubmituserpaper', {
					'id': that.sp.id,
					'userpaperid': that.sr.doing_userpaper.id,
					'usedsecond': (new Date().getTime() / 1000 - that.param.now),
					'operate': operate,
					// values: ret.values,
          values: ret.newvals
          // scoreGroup:ret.scoreGroup,
          // other:ret.other,
				}, function(res) {
					//如果是提交,需要刷新页面
					if (operate == 'submit' || operate == 'forcesubmit') {
						that.cinit();
					}
				}, function(err) {
					that.cinit(that.options);
				})
			},
			_cronSaveUserpage: function() {
				console.log('begin start _cronSaveUserpage');
				let that = this;
				that.si_save = setTimeout(function() {
					let ret = that.$refs.parse.__getVal();
					console.log('interval save=', ret);
					that._saveorsubmituserpaper('save', ret);
				}, 3000);
				// let ret = that.$refs.parse.__getVal();
				// that._saveorsubmituserpaper('save', ret);
			},
		}
	}
</script>

<style scoped lang="scss">
  .body{width: 100%; height: 100vh; background-color: #FFF; display: flex;justify-content: center; box-sizing: border-box; padding-top: 20vh; letter-spacing: 1px;}
	.a-top-notice {
		position: fixed;
		left: 0px;
		top: 0px;
		background-color: #9c9c9c;
		color: red;
		line-height: 60rpx;
		font-size: 36rpx;
		text-align: center;
		width: 100%;
		font-weight: bold;
	}

	.a-top-notice-fillblank {
		height: 60rpx;
	}

	.u-radio-group {
		width: 100%;
	}
  
</style>
